'use strict';

const { Controller } = require('egg');
const mongo = require('../utils/mongo');
const OSS = require('../models/OSS');
const config = require('../../config/db');
const { success, failed } = require('../utils/request');

class ProjectController extends Controller {
  // 获取项目或者组件的代码模板
  async getTemplate() {
    const { ctx } = this;
    const data = await mongo().query('project'); // project 是表的名字
    ctx.body = data;
  }

  // 获取项目的OSS文件
  async getOSSProject() {
    const { ctx } = this;
    let ossProjectType = ctx.query.type; // 项目类型
    const ossProjectName = ctx.query.name; // 项目名称
    if (!ossProjectName) {
      ctx.body = failed('项目名称不存在');
      return;
    }
    if (!ossProjectType) {
      ossProjectType = 'prod';
    }
    let oss;
    if (ossProjectType === 'prod') {
      oss = new OSS(config.OSS_PROD_BUCKET);
    } else {
      oss = new OSS(config.OSS_DEV_BUCKET);
    }
    if (oss) {
      const fileList = await oss.list(ossProjectName);
      ctx.body = success('获取项目名称成功', fileList);
    } else {
      ctx.body = failed('获取项目文件失败');
    }
  }

  // 从 OSS 服务器当中获取已经上床到OSS服务器的文件（打包好的项目文件（dist下面的那些文件））
  async getOSSFile() {
    const { ctx } = this;
    const dir = ctx.query.name;
    const file = ctx.query.file;
    let ossProjectType = ctx.query.tyep;
    if (!dir || !file) {
      ctx.body = failed('请提供OSS文件名称');
      return;
    }
    if (!ossProjectType) {
      ossProjectType = 'prod';
    }
    let oss;
    if (ossProjectType === 'prod') {
      oss = new OSS(config.OSS_PROD_BUCKET);
    } else {
      oss = new OSS(config.OSS_DEV_BUCKET);
    }
    if (oss) {
      const fileList = await oss.list(dir);
      const fileName = `${dir}/${file}`;
      const finalFile = fileList.find(item => item.name === fileName);
      ctx.body = success('获取项目文件成功', finalFile);
    } else {
      ctx.body = failed('获取项目文件失败');
    }
  }

  // redis
  async getRedis() {
    const { ctx, app } = this;
    const { key } = ctx.query; // 获取路由中的参数
    if (key) {
      const value = await app.redis.get(key);
      ctx.body = `redis[${key}]: ${value}`;
    } else {
      ctx.body = '请提供参数key';
    }
  }
}

module.exports = ProjectController;
